package core4.config;


import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import core4.pojo.User;

@Configuration
@ComponentScan("core4")
@PropertySource("classpath:mysql.properties")

public class RootApplicationConfig implements EnvironmentAware {
	
	 Environment env;
	 
	@Bean
	 public DataSource dataSource() throws PropertyVetoException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setDriverClass(env.getProperty("jdbc.driver"));
		dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
		dataSource.setUser(env.getProperty("jdbc.username"));
		dataSource.setPassword(env.getProperty("jdbc.password"));
		return dataSource;
	 }
	
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() throws PropertyVetoException {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource());
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.addLoadedResource("classpath:SqlMapConfig.xml");
		sqlSessionFactory.setConfiguration(configuration);
		return sqlSessionFactory;
	}
	
	@Bean
	public MapperScannerConfigurer cannerConfigurer() {
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setBasePackage("core4.mapper");
		return mapperScannerConfigurer;
	}
	
	@Bean
	public CommonsMultipartResolver multipartResolver() {
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();

		commonsMultipartResolver.setDefaultEncoding("utf-8");
		Long maxsizeLong=(long) 1048576000;
		commonsMultipartResolver.setMaxUploadSize(maxsizeLong);
		commonsMultipartResolver.setMaxInMemorySize(40960);
		commonsMultipartResolver.setResolveLazily(true);
		return commonsMultipartResolver;
	}
	
	@Bean
	public User user() {
		User user=new User();
		user.setUserName("keke");
		System.out.println(env.getProperty("jdbc.password"));
		
		return user;
	}

	@Override
	public void setEnvironment(Environment environment) {
		 this.env=environment;
		 
	}
	
}
